package cn.gzmli.dtt.common.controll;

import cn.gzmli.dtt.common.annotation.Comment;
import cn.gzmli.dtt.common.annotation.Privilege;
import cn.gzmli.dtt.common.config.cache.Config;
import cn.gzmli.dtt.common.entity.*;
import cn.gzmli.dtt.common.utils.BaseUtil;
import cn.gzmli.dtt.common.utils.Constant;
import cn.gzmli.dtt.common.service.MenuService;
import cn.gzmli.dtt.common.utils.BaseController;
import cn.gzmli.dtt.sbzyc.validation.Add;
import cn.gzmli.dtt.sbzyc.validation.Update;
import com.xiaoleilu.hutool.util.StrUtil;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileFilter;
import java.util.*;

/**
 * @Descript 菜单相关接口
 * @Author xsx
 * @Date 2017/12/25
 */
@Controller
@RequestMapping("/menu")
public class MenuController implements BaseController<Menu> {
    @Autowired
    private MenuService menuService;

    @Override
    @RequestMapping("/list")
    @ResponseBody
    @Comment("获取菜单列表")
    public Result list() throws Exception {
        return new Result(Constant.SUCCESS, "获取菜单列表成功", this.menuService.getAll());
    }

    @Override
    @RequestMapping("/listByCondition")
    @ResponseBody
    @Comment("获取菜单列表")
    public Result listByCondition(HttpServletRequest request, PageInfo pageInfo) throws Exception {
        DetachedCriteria condition = DetachedCriteria.forClass(Menu.class);
        if (StrUtil.isNotBlank(request.getParameter("pId"))){
            condition.createAlias("parent", "p").add(Restrictions.eq("p.id", Integer.valueOf(request.getParameter("pId"))));
        }
        condition.addOrder(Order.asc("orderNo"));
        List<Menu> data = this.menuService.getByCondition(condition, pageInfo);
        return new Result(Constant.SUCCESS, "获取菜单列表成功", data, pageInfo);
    }

    @Override
    @RequestMapping("/get")
    @ResponseBody
    @Comment("获取菜单信息")
    public Result get(Integer id) throws Exception {
        return new Result(Constant.SUCCESS, "获取菜单信息成功", this.menuService.get(id));
    }

    @Override
    @RequestMapping("/getByCondition")
    @ResponseBody
    @Comment("获取菜单信息")
    public Result getByCondition(HttpServletRequest request) throws Exception {
        Map<String, String> condition = new HashMap<>();
        return new Result(Constant.SUCCESS, "获取菜单信息成功", this.menuService.getByCondition(condition));
    }

    @Override
    @RequestMapping("/save")
    @ResponseBody
    @Comment("新增菜单信息")
    @Privilege("/menu/save")
    public Result save(@Validated(Add.class)Menu menu) throws Exception {
        return new Result(Constant.SUCCESS, "新增菜单信息成功", this.menuService.save(menu));
    }

    @Override
    @RequestMapping("/update")
    @ResponseBody
    @Comment("修改菜单信息")
    @Privilege("/menu/update")
    public Result update(@Validated(Update.class) Menu menu) throws Exception {
        this.menuService.updateMenu(menu);
        Config.updateMenu(menu);
        return new Result(Constant.SUCCESS, "修改菜单信息成功");
    }

    @Override
    @RequestMapping("/delete")
    @ResponseBody
    @Comment("删除菜单信息")
    @Privilege("/menu/delete")
    public Result delete(Menu menu) throws Exception {
        this.menuService.delete(menu);
        return new Result(Constant.SUCCESS, "删除菜单信息成功");
    }

    @RequestMapping("/listUserMenu")
    @ResponseBody
    @Ignore
    public Result listUserMenu(HttpServletRequest request) throws Exception{
        Set<Menu> menus = new HashSet<>();
        User user = Config.getUser(request);
        Set<Role> roles = user.getRoles();
        for (Role role : roles){
            menus.addAll(role.getMenus());
        }
        return new Result(Constant.SUCCESS, "获取用户菜单成功", menus);
    }

    @RequestMapping("/listUserMenu2")
    @ResponseBody
    @Ignore
    public Result listUserMenu2(HttpServletRequest request) throws Exception{
        Set<Menu> menus = new HashSet<>();
        User user = Config.getUser(request);
        Set<Role> roles = user.getRoles();
        for (Role role : roles){
            menus.addAll(role.getMenus());
        }
        List<Menu> menuList = new ArrayList<>(menus);
        Collections.sort(menuList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return o1.getOrderNo()-o2.getOrderNo();
            }
        });
        return new Result(Constant.SUCCESS, "获取用户菜单成功", menuList);
    }

    @RequestMapping("/listUserMenuByPid")
    @ResponseBody
    @Ignore
    public Result listUserMenuByPid(
            HttpServletRequest request,
            Integer pId
    ) throws Exception{
        return new Result(Constant.SUCCESS, "获取子菜单成功", this.menuService.getUserMenuByPid(Config.getUser(request), pId));
    }

    @RequestMapping(value = "/listIcos.wdf")
    @ResponseBody
    @Ignore
    public Map<String,Object> dataAllByParam(HttpServletRequest request, int pageNo) throws Exception {
        String icoDir=request.getRealPath("/")+"resource\\ico\\menuico";
        FileFilter fileFilter=new FileFilter(){
            @Override
            public boolean accept(File pathname) {
                String tmp=pathname.getName().toLowerCase();
                if(tmp.contains("16x16")&&(tmp.endsWith(".png")||tmp.endsWith(".jpg")||tmp.endsWith(".gif"))){
                    return true;
                }
                return false;
            }
        };

        File ico=new File(icoDir);
        File[] files=ico.listFiles(fileFilter);
        List<Map<String,Object>> icos=new ArrayList<Map<String,Object>>();

        Map<String,Object> result=new HashMap<String,Object>();
        int totalPages;

        if(files.length>50){
            if(files.length%50==0)
            {
                totalPages=files.length/50;
            }
            else{
                totalPages=files.length/50+1;
            }
        }else{
            totalPages=1;
        }
        for(int i=0;i<files.length;i++){
            if(i>=(pageNo-1)*50&&i<(pageNo-1)*50+50){
                Map<String,Object> icoFile=new HashMap<String, Object>();
                icoFile.put("icoUrl","/resource/ico/menuico/"+files[i].getName());
                icoFile.put("icoName",files[i].getName());
                icos.add(icoFile);
            }
        }
        result.put("totalPages",totalPages);
        result.put("icos",icos);
        return result;
    }

    @RequestMapping(value = "/listRoleMenu")
    @ResponseBody
    @Ignore
	public Result lists(HttpServletRequest request, PageInfo pageInfo) throws Exception {
		return new Result(Constant.SUCCESS, "获取角色菜单成功", this.menuService.getRoleAllMenus());
	}

    @RequestMapping({"/listTabMenuById"})
    @ResponseBody
    @Ignore
    public Result listTabMenuById(HttpServletRequest request, Integer menuId) throws Exception {
        List<Map<String, Object>> menuList = new ArrayList();
        if (BaseUtil.isNotEmpty(menuId)) {
            menuList = this.menuService.getTabMenuById(menuId);
        }

        request.getSession().setAttribute("menuList", menuList);
        return new Result(Constant.SUCCESS, "获取子菜单成功", menuList);
    }
}
